package com.fd.wpx.sso.web.shiro.filter;

import com.fd.wpx.authorizating.service.SysUserService;
import com.fd.wpx.blog.pojo.SysUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.Date;

public class ServerFormAuthenticationFilter extends FormAuthenticationFilter {
    @Autowired
    private SysUserService userService;
    @Value("${user}")
    private String user;
    @Value("${index}")
    private String index;

    public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        Subject subject= SecurityUtils.getSubject();
        if(subject.isAuthenticated())
        {
            subject.logout();
        }
        return  this.isAccessAllowed(request, response, mappedValue)||this.onAccessDenied(request, response, mappedValue);
    }
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject = getSubject(request, response);
        return subject.isAuthenticated();

    }
    protected void issueSuccessRedirect(ServletRequest request, ServletResponse response) throws Exception {
        String fallbackUrl = (String) getSubject(request, response)
                .getSession().getAttribute("authc.fallbackUrl");
        if(StringUtils.isEmpty(fallbackUrl)) {
            fallbackUrl = getSuccessUrl();
        }
        Subject subject= SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        SysUser sysUser=(SysUser)userService.findUserByName(username).getData();
        sysUser.setStime(new Date());
        subject.getSession().setAttribute(user,sysUser);
        userService.updateUser(sysUser);
        WebUtils.redirectToSavedRequest(request, response, fallbackUrl);
    }

}